import axios from 'axios';
import store from '../store/index';

export default {
    install (Vue, options) {
        options = options || {};
        // API服务的 baseURL，请求只需使用相对地址即可
        axios.defaults.baseURL = 'https://back.buyclss.cn/';
        // 超时设置
        axios.defaults.timeout = options.timeout || 100000;
        // axios.defaults.withCredentials = true;
        axios.interceptors.request.use(
          config => {
              let token = store.getters.token || '';
              if (!token) {
                  token = localStorage.getItem('token') || '';
              }
              if (token && config.url !== '/login' ) {
                  config.headers.Authorization = token;
              }
              return config;
          },
          err => {
              return Promise.reject(err);
          });

        axios.interceptors.response.use(function (response) {
            if (response.data.code === 1000){
                return Promise.resolve(response.data.data);
            }
            if (response.data.code === 1001){
                return location.href = '/login';
            }
            Message.error(response.data.errMsg)
            return Promise.reject(response.data);
        }, function (error) {
            return Promise.reject(error);
        });
    },
};
